#!/usr/bin/perl -w

package Purl::DB::XML;

use Purl::Attribute;
use XML::Parser;
use Data::Dumper;
use Exporter;

our @EXPORT_OK = qw(load);
our @EXPORT = qw(load);
our @ISA = qw(Exporter);

our $objects;

# initialize the parser
sub load {
    my ( $cur_element, $index, $parser );
    $parser = XML::Parser->new(
        Handlers => {
            Start => \&_handle_start,
            End   => \&_handle_end,
            Char  => \&_handle_char,
        }
    );
    $parser->parsefile("/home/don/mush.db");
    print "DUMPER:" . Dumper($objects[0]) . "\n";
    return \@objects;
}

sub _handle_start {
    my ( $expat, $element, %attrs ) = @_;
    if ( $element eq "object" ) {
        $index = $attrs{'id'};
        $objects[$index] = {};
    }
    else {
        unless ( $element eq "db" ) {
            $objects[$index]{$cur_element} = "" unless ( exists $objects[$index]{$cur_element} );
        }
    }
    $cur_element = $element;
}

sub _handle_char {
    my ( $expat, $text ) = @_;
    chomp($text);
    $text =~ s/\s+$//;
    unless ( ( $cur_element eq "db" ) || ( $cur_element eq "object" ) ) {
        $objects[$index]{$cur_element} .= $text;
    }
}

sub _handle_end {
    my ( $expat, $element ) = @_;
    if ( $element eq "object" ) {
        #Do nothing, for the moment.
        print "End: \@objects has $#objects indices.\n";
    }
}

1;
